<route lang="jsonc" type="page">
{
"style": {
"navigationBarTitleText": "小游戏",
"navigationBarBackgroundColor": "#f39c12",
"navigationBarTextStyle": "white"
}
}
</route>

<script lang="ts" setup>
import {httpGet, httpPost} from '@/http/http'

defineOptions({
  name: 'GameRelax',
})

// 游戏图标映射
const gameIconMap: Record<string, string> = {
  bubble: 'i-mdi-circle-multiple',
  emoji: 'i-mdi-emoticon-happy',
  breathe: 'i-mdi-meditation',
  color: 'i-mdi-palette',
  memory: 'i-mdi-cards',
  draw: 'i-mdi-pencil',
  puzzle: 'i-mdi-puzzle',
}

// 游戏列表
const relaxingGames = ref<any[]>([])
const loading = ref(false)
const isFirstLoad = ref(true)
const lastUpdateTime = ref(0)

// 获取游戏列表
async function getGameList(silent = false) {
  // 静默更新时不显示loading
  if (!silent) {
    loading.value = true
  }

  try {
    const response = await httpGet<any>('/api/miniapp/game/list')

    if (response.code === 200) {
      const newGameList = response.data.map((game: any) => ({
        id: game.gameCode,
        title: game.gameName,
        description: game.gameDesc,
        icon: gameIconMap[game.gameCode] || 'i-mdi-gamepad-variant',
        color: game.gameColor,
        difficulty: game.difficulty,
        playCount: game.playCount,
        path: game.gamePath,
        available: game.available,
      }))

      // 如果是静默更新，只更新游玩次数，避免整个列表的重新渲染
      if (silent && relaxingGames.value.length > 0) {
        relaxingGames.value.forEach((game, index) => {
          if (newGameList[index]) {
            game.playCount = newGameList[index].playCount
          }
        })
      } else {
        relaxingGames.value = newGameList
      }

      lastUpdateTime.value = Date.now()
    } else {
      // 如果接口调用失败，使用默认数据（仅首次加载时）
      if (!silent) {
        loadDefaultGames()
      }
    }
  } catch (error) {
    console.error('获取游戏列表失败:', error)
    // 接口调用失败时使用默认数据（仅首次加载时）
    if (!silent) {
      loadDefaultGames()
    }
  } finally {
    if (!silent) {
      loading.value = false
    }
  }
}

// 加载默认游戏数据（作为备用）
function loadDefaultGames() {
  relaxingGames.value = [
    {
      id: 'bubble',
      title: '戳泡泡',
      description: '点击屏幕上的泡泡，享受破裂的快感',
      icon: 'i-mdi-circle-multiple',
      color: '#6c5ce7',
      difficulty: '简单',
      playCount: '2.3万',
      path: '/pages/relax/game/bubble/index',
      available: true,
    },
    {
      id: 'emoji',
      title: '消灭 Emoji',
      description: '点击屏幕上的表情符号，享受消灭的快感',
      icon: 'i-mdi-emoticon-happy',
      color: '#fd79a8',
      difficulty: '简单',
      playCount: '1.9万',
      path: '/pages/relax/game/emoji/index',
      available: true,
    },
  ]
}

// 记录游戏开始
async function startGame(gameCode: string) {
  try {
    const response = await httpPost<any>(`/api/miniapp/game/start/${gameCode}`)
    if (response.code === 200) {
      console.log('游戏记录创建成功，记录ID:', response.data)

      // 乐观更新：立即增加游玩次数显示，提供更好的用户体验
      const game = relaxingGames.value.find(g => g.id === gameCode)
      if (game) {
        updatePlayCount(game)
      }

      return response.data
    } else {
      console.error('记录游戏开始失败:', response.msg)
      return null
    }
  } catch (error) {
    console.error('记录游戏开始失败:', error)
    return null
  }
}

// 乐观更新游玩次数
function updatePlayCount(game: any) {
  const currentCount = game.playCount
  let count = 0

  // 解析当前次数
  if (currentCount.includes('万')) {
    count = Math.floor(parseFloat(currentCount.replace('万', '')) * 10000)
  } else if (currentCount.includes('k')) {
    count = Math.floor(parseFloat(currentCount.replace('k', '')) * 1000)
  } else {
    count = parseInt(currentCount) || 0
  }

  count += 1

  // 格式化新的次数显示
  if (count >= 10000) {
    const wan = count / 10000.0
    if (wan >= 10) {
      game.playCount = `${wan.toFixed(0)}万`
    } else {
      game.playCount = `${wan.toFixed(1)}万`
    }
  } else if (count >= 1000) {
    const qian = count / 1000.0
    game.playCount = `${qian.toFixed(1)}k`
  } else {
    game.playCount = count.toString()
  }
}

// 导航到游戏页面
async function navigateToGame(game: any) {
  if (game.available) {
    // 先记录游戏开始
    const recordId = await startGame(game.id)

    // 跳转到游戏页面
    uni.navigateTo({
      url: game.path + (recordId ? `?recordId=${recordId}` : ''),
    })
  } else {
    uni.showToast({
      title: '游戏开发中，敬请期待',
      icon: 'none',
    })
  }
}

onLoad(() => {
  getGameList()
  isFirstLoad.value = false
})

onShow(() => {
  // 页面显示时静默刷新游戏列表数据，确保游玩次数等信息是最新的
  // 避免首次加载时重复请求，使用静默更新减少闪烁
  if (!isFirstLoad.value) {
    // 防抖：距离上次更新超过5秒才进行静默更新
    const now = Date.now()
    if (now - lastUpdateTime.value > 5000) {
      getGameList(true) // 静默更新
    }
  }
})
</script>

<template>
  <view class="game-relax-container">
    <!-- 顶部说明 -->
    <view class="header-section">
      <view class="header-title">
        小游戏
      </view>
      <view class="header-desc">
        简单有趣的小游戏，放松心情，缓解压力
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-text">正在加载游戏列表...</view>
    </view>

    <!-- 游戏网格 -->
    <view v-else class="games-grid">
      <view
          v-for="game in relaxingGames"
          :key="game.id"
          class="game-card"
          :class="{ disabled: !game.available }"
          @click="navigateToGame(game)"
      >
        <view class="game-background"
              :style="{ background: `linear-gradient(135deg, ${game.color}, ${game.color}dd)` }">
          <view :class="game.icon" class="game-icon"/>
          <view class="game-info">
            <view class="game-title">
              {{ game.title }}
            </view>
            <view class="game-desc">
              {{ game.description }}
            </view>
            <view class="game-meta">
              <text class="difficulty">{{ game.difficulty }}</text>
              <text class="play-count">{{ game.playCount }}次游玩</text>
            </view>
            <view v-if="!game.available" class="coming-soon-badge">
              敬请期待
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 小贴士 -->
    <view class="tips-section">
      <view class="tips-title">
        小贴士
      </view>
      <view class="tips-content">
        <view class="tip-item">
          🎮 每个游戏都有不同的放松效果
        </view>
        <view class="tip-item">
          🧘‍♀️ 建议在安静的环境下进行
        </view>
        <view class="tip-item">
          ⏰ 每次游戏时间控制在15-30分钟
        </view>
        <view class="tip-item">
          💤 睡前游戏有助于改善睡眠质量
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.game-relax-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f39c12 0%, #f5b041 100%);
  padding: 20rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

// 顶部区域
.header-section {
  text-align: center;
  padding: 40rpx 30rpx;
  color: #fff;
  margin-bottom: 20rpx;
}

.header-title {
  font-size: 44rpx;
  font-weight: 700;
  margin-bottom: 16rpx;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.header-desc {
  font-size: 28rpx;
  opacity: 0.9;
  text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.2);
}

// 加载状态
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80rpx 0;
}

.loading-text {
  color: #fff;
  font-size: 28rpx;
  opacity: 0.8;
}

// 游戏网格
.games-grid {
  padding: 0 10rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.game-card {
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  }

  &.disabled {
    opacity: 0.7;

    .game-background::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
      z-index: 2;
    }
  }
}

.game-background {
  padding: 30rpx;
  color: #fff;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10rpx);
    z-index: 0;
  }
}

.game-icon {
  font-size: 64rpx;
  text-align: center;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 1;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20rpx;
  color: #fff;
}

.game-info {
  position: relative;
  z-index: 1;
}

.game-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 12rpx;
  text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.2);
}

.game-desc {
  font-size: 24rpx;
  line-height: 1.4;
  margin-bottom: 16rpx;
  opacity: 0.9;
}

.game-meta {
  display: flex;
  justify-content: space-between;
  font-size: 22rpx;
  opacity: 0.8;
  margin-bottom: 8rpx;
}

.coming-soon-badge {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  background: rgba(255, 255, 255, 0.9);
  color: #f39c12;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  font-weight: 600;
  z-index: 3;
}

// 小贴士区域
.tips-section {
  background: rgba(255, 255, 255, 0.95);
  margin: 20rpx 10rpx;
  padding: 30rpx;
  border-radius: 24rpx;
  backdrop-filter: blur(10rpx);
}

.tips-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 24rpx;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.tip-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  padding: 12rpx 0;
}

// 响应式适配
@media screen and (min-width: 768rpx) {
  .games-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>